package com.ddf.jose.controller;

import com.ddf.publics.config.Utill;
import com.ddf.publics.entity.*;
import com.ddf.publics.service.*;
import com.ddf.publics.tool.Constant;
import com.ddf.publics.utils.DatesUtil;
import com.ddf.publics.utils.RedisUtil;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.ibatis.annotations.Arg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName: indexController.java
 * @Description: 首页
 * @author: Jose
 * @date:  2020/6/14 19:37
 * @version V1.0
 */
@Controller
public class indexController {

    @Autowired
    private NoticeService noticeService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private ConversionService conversionService;
    @Autowired
    private CommodityService commodityService;
    @Autowired
    private CommodityRecordService commodityRecordService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private UserCouponService userCouponService;
    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private UserOrderService userOrderService;
    @Resource
    private SpecimensService specimensService;
    //进入个人中心首页
    @RequestMapping({"/index","/"})
    public String accMain(Model model){
        model.addAttribute("ImgNotice",noticeService.listImgNotice());
        model.addAttribute("pList",specimensService.queryTopThree());
        return "index";
    }
    //进入我的地址
    @RequestMapping("/myAddress")
    public String myAddress(){
        return "/userInfo/myAddress";
    }

    @RequestMapping("/newGuider")
    public String newGuider(){
        return "pages/newGuider";
    }
    @RequestMapping("/order")
    public String order(){
        return "userInfo/myOrder";
    }

    /**
     * @description 公告、广告
     * @author jose
     * @date 2020/6/18 16:30
     * @params [model]
     * @return java.lang.String
     */
    @RequestMapping("notice")
    public String notice(Model model){
        model.addAttribute("listNotice",noticeService.listNotice());
        return "pages/notice";
    }

    /**
     * @description 签到功能
     * @author jose
     * @date 2020/6/18 16:31
     * @params [day, type, principal]
     * @return java.util.Map
     */
    @RequestMapping(value = "/sign_in",method = RequestMethod.POST)
    @ResponseBody
    public Map Sign_in(Integer day,Integer type,Principal principal){
        Map modelMap = new HashMap();
        User user = loginService.queryByPhone(principal.getName());
        String redisName = "sign:"+user.getPhone();
        //获取当前登录的用户获取今天是否签到 签到 返回 true
        boolean an = redisUtil.getBit("sign:" + user.getPhone(), day);
        //如果type等于1表示用户点击了签到 如果等于2用户点击了查看
        if(type == 1) {
            if (an) {
                modelMap.put("whether", "yes");
            } else {
                modelMap.put("whether", "no");
                //添加一个签到数据在redis中
                try {
                    redisTemplate.opsForValue().setBit(redisName, day, true);
                }catch (Exception e){
                    modelMap.put("whether", "error");
                }

                //给当前登录的用户添加积分
                userService.userAddPoint(user,Constant.SIGN_IN_POINTS);
                //把获得的积分记录在数据库中
                conversionService.userIntegralRecord(user,Constant.SIGN_IN_POINTS,Constant.INTEGRAL_ACQUISITION);
            }
            return modelMap;
        } else if(type == 2) {
            List qiandao = new ArrayList<>();
            List noQiandao = new ArrayList();

            int flag = 0;
            for (int i = 1; i <= day; i++) {
                boolean bit = redisUtil.getBit("sign:" + user.getPhone(), i);
                if (bit) {
                    flag++;
                    //获取用户签到过的日期
                    qiandao.add(i);
                } else {
                    //获取用户没有签到过的日期
                    noQiandao.add(i);
                    flag = 0;
                }
            }
            Calendar cale = new GregorianCalendar();
            cale.add(Calendar.MONTH, 1);
            cale.set(Calendar.DAY_OF_MONTH, 0);
            Integer CountDay = cale.getTime().getDate();
            modelMap.put("yesSign", qiandao);
            modelMap.put("noSign", noQiandao);

            Object look = redisUtil.get("look:" + user.getPhone());

//            if (look == "7") {
//                return modelMap;
//            }
//            if (flag == 3) {
//                redisUtil.set("look:" + user.getPhone(), 7);
//                modelMap.put("whether", "7");
//                //给当前登录的用户添加积分
//                userService.userAddPoint(user, Constant.INVAESTMENT_SEVEN);
//                //把获得的积分记录在数据库中
//                conversionService.userIntegralRecord(user, Constant.INVAESTMENT_SEVEN, Constant.CONTINUOUS_SIGN_IN_REWARD);
//            }
            if (look == "7") {
                return modelMap;
            }
            if (flag == 7) {
                redisUtil.set("look:" + user.getPhone(), "7",10);
                modelMap.put("whether", "7");
                //给当前登录的用户添加积分
                userService.userAddPoint(user, Constant.INVAESTMENT_SEVEN);
                //把获得的积分记录在数据库中
                conversionService.userIntegralRecord(user, Constant.INVAESTMENT_SEVEN, Constant.CONTINUOUS_SIGN_IN_REWARD);
            }
            if (look == "15") {
                return modelMap;
            }
            if (flag == 15) {
                redisUtil.set("look:" + user.getPhone(), "15",172800);
                modelMap.put("whether", "15");
                //给当前登录的用户添加积分
                userService.userAddPoint(user, Constant.INVAESTMENT_FIFTEEN);
                //把获得的积分记录在数据库中
                conversionService.userIntegralRecord(user, Constant.INVAESTMENT_FIFTEEN, Constant.CONTINUOUS_SIGN_IN_REWARD);
            }
            if (look == "25") {
                return modelMap;
            }
            if (flag == 25) {
                redisUtil.set("look:" + user.getPhone(), "25",172800);
                modelMap.put("whether", "25");
                //给当前登录的用户添加积分
                userService.userAddPoint(user, Constant.INVAESTMENT_TWENTYFIVE);
                //把获得的积分记录在数据库中
                conversionService.userIntegralRecord(user, Constant.INVAESTMENT_TWENTYFIVE, Constant.CONTINUOUS_SIGN_IN_REWARD);
            }
            if (look == String.valueOf(CountDay)) {
                return modelMap;
            }
            if (flag == CountDay) {
                redisUtil.set("look:" + user.getPhone(), CountDay + "",172800);
                modelMap.put("whether", "max");
                //给当前登录的用户添加积分
                userService.userAddPoint(user, Constant.INVAESTMENT_MAX);
                //把获得的积分记录在数据库中
                conversionService.userIntegralRecord(user, Constant.INVAESTMENT_MAX, Constant.CONTINUOUS_SIGN_IN_REWARD);
            }

        }
        return modelMap;
    }

    //补签
    @RequestMapping("/buqian")
    @ResponseBody
    public Map<String,Object> buqian(Integer day,Principal principal){
        Map map = new HashMap();
        User user = loginService.queryByPhone(principal.getName());
        String redisName = "sign:"+user.getPhone();
        if(user.getResiduePoint() < 10){
            map.put("whether", "InsufficientPoints");
        }else {
            try {
                redisTemplate.opsForValue().setBit(redisName,day,true);

            }catch (Exception e){
                map.put("whether", "error");
            }

            //减去用户积分
            user.setResiduePoint(user.getResiduePoint()-Constant.SIGN_IN_POINTS);
            userService.update(user);

            //积分记录
            Conversion conversion = new Conversion();
            conversion.setGetintegral(-Constant.SIGN_IN_POINTS);
            conversion.setSource(Constant.SUPPLEMENTARY_SIGNATURE+"-"+Constant.SIGN_IN_POINTS);
            conversion.setUserId(user.getId());
            conversion.setEventDate(new Date());
            conversionService.insert(conversion);
            map.put("whether", "yes");
        }

        return map;
    }

    /**
     * @description 商城
     * @author jose
     * @date 2020/6/18 16:31
     * @params []
     * @return java.lang.String
     */
    @RequestMapping("/shopping_mall")
    public String shopping_mall(){
        return "pages/shopping_mall";
    }
    //食用分页
    @RequestMapping("/shiwuList")
    @ResponseBody
    public Map<String,Object> shiwuList(Page page){
        Map map = new HashMap();
        page.setAllCount(commodityService.shiwuListCount());
        page.setCount(6);
        map.put("page",page);
        map.put("obj",commodityService.shiwuList(page));
        return map;
    }
    //电子产品分页
    @RequestMapping("/dianziList")
    @ResponseBody
    public Map<String,Object> dianziList(Page page){
        Map map = new HashMap();
        page.setAllCount(commodityService.dainziListCount());
        page.setCount(6);
        map.put("page",page);
        map.put("obj",commodityService.dainziList(page));
        return map;
    }
    //日常用品分页
    @RequestMapping("/lifeList")
    @ResponseBody
    public Map<String,Object> lifeList(Page page){
        Map map = new HashMap();
        page.setAllCount(commodityService.lifeListCount());
        page.setCount(6);
        map.put("page",page);
        map.put("obj",commodityService.lifeList(page));
        return map;
    }
    //日常用品分页
    @RequestMapping("/couponList")
    @ResponseBody
    public Map<String,Object> couponList(Page page,Principal principal){
        User user = loginService.queryByPhone(principal.getName());
        Map map = new HashMap();
        page.setAllCount(couponService.couponCount());
        page.setCount(6);
        map.put("page",page);
        map.put("obj",couponService.couponList(page));
        return map;
    }
    //物品兑换
    @RequestMapping("/point_exchange")
    @ResponseBody
    public String point_exchange(Integer id,Integer jifen,String name,Principal principal){
        Commodity CR = commodityService.queryById(id);
        if(CR.getGoodsStock() == 0){
            return "soldOut";
        }
        User user = loginService.queryByPhone(principal.getName());
        if(user.getPhone() != null){
            if(user.getResiduePoint() >= jifen){
                //减去用户积分
                user.setResiduePoint(user.getResiduePoint()-jifen);
                userService.update(user);


                //对库存减少1 已售加1
                if(!(CR.getGoodsStock() <= 0)){
                    CR.setGoodsStock(CR.getGoodsStock()-1);
                    CR.setGoodsSell(CR.getGoodsSell()+1);
                    commodityService.update(CR);
                }else {
                    return "库存不足";
                }
                Conversion conversion = new Conversion();
                conversion.setGetintegral(-Constant.SIGN_IN_POINTS);
                conversion.setSource(Constant.PURCHASE_ITEMS +"-"+ Constant.SIGN_IN_POINTS);
                conversion.setUserId(user.getId());
                conversion.setEventDate(new Date());
                conversionService.insert(conversion);

                //兑换商品增加记录
                CommodityRecord commodityRecord = new CommodityRecord();
                commodityRecord.setCommodityName(name);
                commodityRecord.setCommodityPrice(jifen);
                commodityRecord.setExchangeTime(new Date());
                commodityRecord.setCommodityType(CR.getGoodsType());
                commodityRecord.setUserId(user.getId());
                commodityRecordService.insert(commodityRecord);
                return "成功";
            }else {
                return "积分不足";
            }
        }else {
            return "未登录";
        }

    }

    // 优惠券兑换
    @RequestMapping("/coupon_exchange")
    @ResponseBody
    public String coupon_exchange(Integer id,Integer jifen,String name,Integer outTime,Principal principal) throws ParseException {
        User user = loginService.queryByPhone(principal.getName());
        if(user.getPhone() != null){
            if(user.getResiduePoint() >= jifen){
                //减去用户积分
                user.setResiduePoint(user.getResiduePoint()-jifen);
                userService.update(user);

                //积分记录
                Conversion conversion = new Conversion();
                conversion.setGetintegral(-Constant.SIGN_IN_POINTS);
                conversion.setSource("优惠券-" + Constant.SIGN_IN_POINTS);
                conversion.setUserId(user.getId());
                conversion.setEventDate(new Date());
                conversionService.insert(conversion);

                //兑换商品增加记录
                CommodityRecord commodityRecord = new CommodityRecord();
                commodityRecord.setCommodityName(name);
                commodityRecord.setCommodityPrice(jifen);
                commodityRecord.setExchangeTime(new Date());
                commodityRecord.setUserId(user.getId());
                commodityRecord.setCommodityType(Constant.RED_PRODUCTS);
                commodityRecordService.insert(commodityRecord);

                //给用户添加优惠券
                UserCoupon userCoupon = new UserCoupon();
                userCoupon.setUserId(user.getId());
                userCoupon.setCouponId(id);
                Calendar cal = new GregorianCalendar();
                cal.add(Calendar.DAY_OF_MONTH,outTime); //将当前时间加多少天
                Date date = cal.getTime(); //获取添加完后的时间
                userCoupon.setExpirationDate(date);
                userCoupon.setExchangeTime(new Date());
                userCoupon.setCouponState(Constant.NOT_USED);
                UserCoupon u = userCouponService.insert(userCoupon);

                //设置键过期时间
                long begin;
                long end;
                begin= userCoupon.getExchangeTime().getTime();
                end = userCoupon.getExpirationDate().getTime();
                int time = (int)((end - begin) / 1000); //计算开始时间到结束时间一共多少秒
                redisUtil.set("coupon:"+u.getId(),"猪心",time);

                return "成功";
            }else {
                return "积分不足";
            }
        }else {
            return "未登录";
        }

    }
    /**
     * @description 优惠券
     * @author jose
     * @date 2020/6/17 8:23
     * @params []
     * @return java.lang.String
     */
    @GetMapping(value = "/myCoupon")
    public String integral() {
        return "userInfo/integral";
    }


    //我的优惠券列表
    @RequestMapping("/myCouponList")
    @ResponseBody
    public Map<String,Object> myCouponList(Page page,Integer state,Integer money,Principal principal){
        User user = loginService.queryByPhone(principal.getName());
        page.setAllCount(userCouponService.userCouponCount(user.getId(),state));
        page.setCount(8);
        Map map = new HashMap();
        map.put("page",page);
        map.put("obj",userCouponService.myCouponList(page,user.getId(),state));
        return map;
    }

    //查询可用优惠券
    @RequestMapping("/usableCouponList")
    @ResponseBody
    public Map<String,Object> usableCouponList(Integer money,Principal principal){
        User user = loginService.queryByPhone(principal.getName());
        Map map = new HashMap();
        if(money != null){
            map.put("coupon",userCouponService.usableCoupon(money,user.getId()));
        }
        return map;
    }

    /**
     * @description 我的地址
     * @author jose
     * @date 2020/6/27 19:57
     * @params [page, principal]
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @RequestMapping("address")
    @ResponseBody
    public String address(UserAddress userAddress,Principal principal){
        User user = loginService.queryByPhone(principal.getName());
        userAddress.setUserId(user.getId());
        userAddress.setState(0);

        int count = userAddressService.addressCount(user.getId());
        if(count >= 5){
            return "no";
        }else {
            userAddressService.insert(userAddress);
            return "yes";
        }

    }

    //地址个数
    @RequestMapping("/count")
    @ResponseBody
    public Integer count(Principal principal){
        User user = loginService.queryByPhone(principal.getName());
        int count = userAddressService.addressCount(user.getId());
        return count;
    }
    //设置默认
    @RequestMapping("/editState")
    @ResponseBody
    public Integer editmoren(Integer id,Principal principal){
        User user = loginService.queryByPhone(principal.getName());
        userAddressService.editAllState(user.getId());
        userAddressService.editState(id);
        return 0;
    }
    //将所有为1的值变为0
    @RequestMapping("/editAllState")
    @ResponseBody
    public Integer editAllmoren(Principal principal){
        User user = loginService.queryByPhone(principal.getName());
        userAddressService.editAllState(user.getId());
        return 0;
    }
    //编辑地址
    @RequestMapping("/editAddress")
    @ResponseBody
    public String editAddress(UserAddress userAddress){
        userAddressService.update(userAddress);
        return "yes";
    }
    //删除地址
    @RequestMapping("/delAddress")
    @ResponseBody
    public String delAddress(Integer id){
        userAddressService.deleteById(id);
        return "yes";
    }
    //查询所有当前登入用户的地址
    @RequestMapping("selAddress")
    @ResponseBody
    public List<Map> selAddress(Principal principal){
        User user = loginService.queryByPhone(principal.getName());
        List<Map> list = userAddressService.selAddress(user.getId());
        return list;
    }

     //兑换历史列表
    @RequestMapping("/exchange_list")
    @ResponseBody
    public Map<String,Object> exchange_list(Page page,Principal principal){
        User user = loginService.queryByPhone(principal.getName());
        Map map = new HashMap();
        page.setAllCount(commodityRecordService.exchange_count(user.getId()));
        page.setCount(8);
        map.put("page",page);
        map.put("obj",commodityRecordService.exchange_list(user.getId(),page));
        return map;
    }

    //添加订单
    @RequestMapping("/orderAdd")
    @ResponseBody
    public String orderAdd(UserOrder userOrder,Principal principal){
        User user = loginService.queryByPhone(principal.getName());
        userOrder.setUserId(user.getId());
        userOrder.setOrderState(Constant.TO_BE_DELIVERED);
        try {
            userOrderService.insert(userOrder);
        }catch (Exception e){
            return "error";
        }
        return "yes";
    }

    //订单列表
    @RequestMapping("/orderList")
    @ResponseBody
    public Map<String,Object> orderList(Integer page,Integer limit,Principal principal){
        User user = loginService.queryByPhone(principal.getName());
        if(page==null){
            page=1;
        }
        if(limit == null){
            limit = 10;
        }
        int offset = (page-1)*limit;
        Map  map = new HashMap();
        map.put("code","0");
        map.put("msg","提示");
        map.put("count",userOrderService.orderCount(user.getId()));
        map.put("data",userOrderService.queryAllByLimit(offset,limit,user.getId()));
        return map;
    }

    //后台订单列表
    @RequestMapping("/MorderList")
    @ResponseBody
    public Map<String,Object> MorderList(Integer page,Integer limit){
        if(page==null){
            page=1;
        }
        if(limit == null){
            limit = 10;
        }
        int offset = (page-1)*limit;
        Map  map = new HashMap();
        map.put("code","0");
        map.put("msg","提示");
        map.put("count",userOrderService.MorderCount());
        map.put("data",userOrderService.MqueryAllByLimit(offset,limit));
        return map;
    }

    //收货
    @RequestMapping("/ReceivingGoods")
    @ResponseBody
    public String ReceivingGoods(Integer id){
        UserOrder userOrder = new UserOrder();
        userOrder.setOrderId(id);
        userOrder.setOrderState(Constant.RECEIVED);
        userOrder.setReceivingTime(new Date());
        try {
            userOrderService.update(userOrder);
        }catch (Exception e){
            return "error";
        }
        return "yes";
    }



}
